# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo

import json
import requests

from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def gen_var_ticks():
  price_list = [
      1e9,
      1000000.,
      500000.,
      100000,
      50000.,
      10000.,
      5000.,
      1000.,
      100.,
      10.,
      1,
      0]
  tick_list = [
      1000.,
      500.,
      100.,
      50.,
      10.,
      5.,
      1.,
      0.1,
      0.01,
      0.001,
      0.0001]

  range_list = list(zip(price_list[:-1], price_list[1:]))
  result = []
  for r, tick in zip(range_list, tick_list):
    assert r[0] > r[1]
    info = {
        'from': r[1],
        'to': r[0],
        'value': tick,
    }
    result.append([info['from'], info['to'], info['value']])
  return result


def generate():
  mea = 'Spot.Bithumb.v2'
  me = '.'.join(mea.split('.')[:2])
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get("https://api.bithumb.com/public/ticker/ALL").json()['data']

  pis = []
  for symbol, info in data.items():
    if not isinstance(info, dict):
      continue

    native_symbol = symbol
    native_base = symbol
    native_quote = 'KRW'
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=gen_var_ticks(),
        qty_ticksize=0.0001,
        min_amount=500, # based on the pilot, min_amount is 500 KRW
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  data = requests.get("https://api.bithumb.com/public/ticker/ALL_BTC").json()['data']
  for symbol, info in data.items():
    if not isinstance(info, dict):
      continue
    native_symbol = symbol + '_BTC'
    native_base = symbol
    native_quote = 'BTC'
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)
    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=0.00000001,
        qty_ticksize=0.0001,
        min_amount=0.0002,
    )
    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  base_currency_list = [info['native_base'] for info in data]
  currency_list = base_currency_list + quote_currency_list
  res = {
      'coin_list': list(set(base_currency_list)),
  }
  return res


def get_bithumb_cointype():
  url = 'https://r2.bithumb.com/resources/js/language/english_lang_new.js?v=bithumb.2.0'
  content = requests.get(url).text
  lines = [line.strip() for line in content.split('\n') if 'core.coin.msgC' in line]
  lines = [line.replace('core.coin.msg', '') for line in lines]
  lines = [line.replace(',', '') for line in lines]
  lines = [line.replace("'", '"') for line in lines]
  content = '{' + ','.join(lines) + '}'
  data = json.loads(content)
  return data


if __name__ == "__main__":
  print(json.dumps(generate(), indent=2))
